#!/usr/bin/python

#  Copyright 2010 Gregory Szorc
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

# This is a compiler plugin for protoc
# see http://code.google.com/apis/protocolbuffers/docs/reference/other.html
#
# It produces C++ code that defines Lua userdata types for protocol buffer
# messages. This C++ code makes calls to the C++ code generated by Google's
# C++ generator that ships with Protocol Buffers.
#
# Like the C++ generator, we put all messages from the same file into the
# same output file.
#
# Yes, it is currently written in Python. That's how bootstrapping works,
# people.

from lua_protobuf.generator import file_source, file_header, lua_protobuf_header, lua_protobuf_source
from google.protobuf.descriptor import FieldDescriptor
from google.protobuf.compiler.plugin_pb2 import CodeGeneratorRequest, CodeGeneratorResponse
from sys import stdin, stdout, stderr

# Python 3 should use binary buffer object
try:
    stdin = stdin.buffer
except AttributeError:
    pass
try:
    stdout = stdout.buffer
except AttributeError:
    pass

serialized = stdin.read()
request = CodeGeneratorRequest()
request.ParseFromString(serialized)

response = CodeGeneratorResponse()

# each input file to the compiler
for i in range(0, len(request.proto_file)):
    file_descriptor = request.proto_file[i]
    filename = file_descriptor.name
    package = file_descriptor.package

    # for now, we require package, which is bad
    # TODO fix this
    if not package:
        response.error = 'file seen without package. lua-protobuf currently requires a package on every proto file: %s' % filename
        break

    define_value = package.replace('.', '_').upper()
    cpp_header = '%s.pb.h' % package.replace('.', '/')
    cpp_namespace = '::%s' % package.replace('.', '::')

    f = response.file.add()
    f.name = '%s.pb-lua.h' % package.replace('.', '/')
    f.content = file_header(file_descriptor)

    f = response.file.add()
    f.name = '%s.pb-lua.cc' % package.replace('.', '/')
    f.content = file_source(file_descriptor)

f = response.file.add()
f.name = 'lua-protobuf.h'
f.content = lua_protobuf_header()

f = response.file.add()
f.name = 'lua-protobuf.cc'
f.content = lua_protobuf_source()

stdout.write(response.SerializeToString())
exit(0)

